import json
import time
from datetime import datetime, timedelta

import asyncio
import httpx
from asgiref.sync import sync_to_async
from icecream import ic
from requests import Session
from requests.auth import HTTPBasicAuth  # or HTTPDigestAuth, or OAuth1, etc.
from zeep import Client
from zeep.transports import Transport
import requests
import dbconnect

import logging

from main import clients

async def sender_to_1c(DocNum: str, con_key: str, NewErr: str=None, NewTemp: str=None):
    url = 'http://193.46.65.27:51081/ukt_dev1/hs/Request/Refbot/EditRJ?guidJ={DocNum}&guidCont={con_key}&Alarm={NewErr}&Tfact={NewTemp}'
    async with httpx.AsyncClient() as client:
        while True:
            try:
                r = await client.get(url.format(DocNum=DocNum, con_key=con_key, NewErr=NewErr if NewErr is not None else '', NewTemp=NewTemp if NewTemp is not None else ''),
                                     auth=(dbconnect.http_login, dbconnect.http_pwd))
                if r.status_code != 200:
                    logging.info("Wrong answer code " + str(r.status_code))
                    await asyncio.sleep(5)
                    continue
                else:
                    return r
            except:
                logging.info("Unable to find host or timeout")
                await asyncio.sleep(1)
        return r



async def client_get_post():
    async with httpx.AsyncClient() as client:
        return client


# logging.basicConfig(format='%(asctime)s:%(message)s',filename='Http.log', level=logging.INFO)

async def send_odata_get(object_name, params={}):
    async with httpx.AsyncClient() as client:
        url = dbconnect.odata_url
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        param_str = '?$format=json' + (
            (''.join(['&$%s=%s' % (key, value) for (key, value) in params.items()])).replace("`", "%27")).replace(" ",
                                                                                                                  "%20")
        while True:
            try:
                r = await client.get(url + (object_name.replace("`", "%27")).replace(" ", "%20") + param_str, auth=auth)
                if r.status_code != 200:
                    logging.info("Wrong answer code " + str(r.status_code))
                    await asyncio.sleep(5)
                    # Попробуем снова на следующей итерации цикла
                    continue
                else:
                    return r
            except:
                logging.info("Unable to find host or timeout")
                await asyncio.sleep(1)


async def asend_odata_get(object_name, params={}):
    async with httpx.AsyncClient() as client:
        url = dbconnect.odata_url
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        param_str = '?$format=json' + (
            (''.join(['&$%s=%s' % (key, value) for (key, value) in params.items()])).replace("`", "%27")).replace(" ",
                                                                                                                  "%20")
        while True:
            try:
                r = await client.get(url + (object_name.replace("`", "%27")).replace(" ", "%20") + param_str, auth=auth)
                if r.status_code != 200:
                    logging.info("Wrong answer code " + str(r.status_code))
                    time.sleep(5)
                    # Попробуем снова на следующей итерации цикла
                    continue
                else:
                    return r
            except:
                logging.info("Unable to find host or timeout")
                time.sleep(1)


async def jurnal_list2(numbers=None):
    client = await  client_get_post()
    text = 'b6d0d3f0-f766-11ee-9b15-00155d03f700'
    url = 'http://193.46.65.27:51081/ukt_dev1/hs/Request/Refbot/GetObjByGuid?guid='
    if numbers is not None:
        url += numbers
    auth = (dbconnect.http_login, dbconnect.http_pwd)
    while True:
        try:
            r = await client.get(url, auth=auth)
            if r.status_code != 200:
                await asyncio.sleep(5)
                # Попробуем снова на следующей итерации цикла
                continue
            else:
                return r
        except:
            await asyncio.sleep(1)


async def get_data(ref_key: str):
    auth = (dbconnect.http_login, dbconnect.http_pwd)
    async with httpx.AsyncClient() as async_client:
        response = await async_client.get('http://193.46.65.27:51081/ukt_dev1/hs/Request/Refbot/GetObjByGuid?guid=' + ref_key, auth=auth)
        return response.json()


async def jurnal_list(numbers=None):
    async with httpx.AsyncClient() as async_client:
        url = 'http://193.46.65.27:51081/ukt_dev1/hs/Request/Refbot/GetRJ'
        if numbers is not None:
            url += '?numbers=' + numbers
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        while True:
            try:
                r = await async_client.get(url, auth=auth)
                if r.status_code != 200:
                    await asyncio.sleep(5)
                    # Попробуем снова на следующей итерации цикла
                    continue
                else:
                    return r
            except:
                await asyncio.sleep(1)


async def getlastref(User_Ref_Key,new_Jornal):

    CurrDate = (datetime.now() - timedelta(hours=4, minutes=0, seconds=0)).strftime("%Y-%m-%dT%H:%M:%S")
    text_request = {
        "filter": "Posted eq true and DeletionMark eq false and РегламентноеСоздание eq true and Date gt datetime`" + CurrDate + "`",
        "orderby": "Date desc",
        "top": "1"}

    request = await send_odata_get("Document_ЖурналОбходовРефов",
                             text_request)

    data = request.json()
    # neJournal = 1 then new doc
    if data['value'] and new_Jornal != "1":
        retr = {
            "Ref_Key": data['value'][0]['Ref_Key'],
            "Number": data['value'][0]['Number'],
            "Date": data['value'][0]['Date'],
            "List": []
        }

        text_request = {
            "filter": 'Ref_Key eq guid`' + data['value'][0]['Ref_Key'] + '`',
            "expand": 'Контейнер',
            'orderby': 'LineNumber'}

        request2 = await send_odata_get("Document_ЖурналОбходовРефов_Контейнеры",
                                  text_request)
        data = request2.json();
        retr['List'].append(data['value'])
        return retr
    else:
        long_text = {
            "Сотрудник_Key": User_Ref_Key,
            "Примечание": "Created by @ReffApp",
            "РегламентноеСоздание": "true"}
        update_req = await send_odata_post('Document_ЖурналОбходовРефов', long_text)

        await fillRJ(update_req.json()['Ref_Key'])

        text_request = {
            "filter": "Ref_Key eq guid`" + update_req.json()['Ref_Key'] + "`"}

        request = await send_odata_get("Document_ЖурналОбходовРефов",
                                 text_request)

        data = request.json()
        retr = {
            "Ref_Key": data['value'][0]['Ref_Key'],
            "Number": data['value'][0]['Number'],
            "Date": data['value'][0]['Date'],
            "List": []
        }

        text_request = {
            "filter": 'Ref_Key eq guid`' + data['value'][0]['Ref_Key'] + '`',
            "expand": 'Контейнер',
            'orderby': 'LineNumber'}

        request2 = await send_odata_get("Document_ЖурналОбходовРефов_Контейнеры",
                                  text_request)
        data = request2.json();
        retr['List'].append(data['value'])
        return retr


async def updateRefJournal(DocNum, Ref_Key, Alarm, Fact_Temp):
    text_request = {
        "filter": "Number eq `" + DocNum + "`"}
    request = await send_odata_get("Document_ЖурналОбходовРефов",
                             text_request)
    data = request.json()
    now = datetime.now()
    long_text = {'Контейнеры': []}
    for i in range(len(data['value'][0]['Контейнеры'])):
        if data['value'][0]['Контейнеры'][i]['Контейнер_Key'] == Ref_Key:
            data['value'][0]['Контейнеры'][i]['ДатаОсмотра'] = str(now.strftime("%Y-%m-%dT%H:%M:%S"))
            data['value'][0]['Контейнеры'][i]['ФактическаяT'] = Fact_Temp
            data['value'][0]['Контейнеры'][i]['Alarm'] = Alarm
        long_text['Контейнеры'].append(
            {
                'Ref_Key': data['value'][0]['Ref_Key'],
                'LineNumber': str(data['value'][0]['Контейнеры'][i]['LineNumber']),
                'Контейнер_Key': str(data['value'][0]['Контейнеры'][i]['Контейнер_Key']),
                'МестоРазмещения': str(data['value'][0]['Контейнеры'][i]['МестоРазмещения']),
                'НормативнаяT': str(data['value'][0]['Контейнеры'][i]['НормативнаяT']),
                'ФактическаяT': str(data['value'][0]['Контейнеры'][i]['ФактическаяT']),
                'Alarm': str(data['value'][0]['Контейнеры'][i]['Alarm']),
                'Груз': str(data['value'][0]['Контейнеры'][i]['Груз']),
                'ДатаОсмотра': data['value'][0]['Контейнеры'][i]['ДатаОсмотра']}

        )

    update_req = await send_odata_patch('Document_ЖурналОбходовРефов(guid`' + data['value'][0]['Ref_Key'] + '`)',
                                  long_text)


async def get_users_list():
    text_request = {"select": "Ref_Key,ПолноеНаименование",
                    "filter": "ДолжностьСотрудника_Key eq guid`563e4aa7-5aa0-435e-9ded-06d410d8865b` and DeletionMark eq false"}
    request = await send_odata_get("Catalog_Сотрудники", text_request)
    data = request.json()
    if len(data['value']) != 0:
        return {
            'ResponceCode': '1',
            'ResponceText': 'list of users',
            'UserList': data['value']
        }
    else:
        return {
            'ResponceCode': '0',
            'ResponceText': 'No users found',
            'UserList': ''
        }


async def fillRJ(guid):
    async with httpx.AsyncClient() as client:
        url = dbconnect.FillRJ_url + "?guid=" + guid
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        try:
            r = await client.get(url, auth=auth)
            return r
        except:
            await asyncio.sleep(1)


async def send_odata_post(object_name, data={}):
    async with httpx.AsyncClient() as client:
        url = dbconnect.odata_url
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        count_error = 0

        for key in data:
            if isinstance(data[key], dict):
                for key2 in data[key]:
                    if isinstance(data[key][key2], str):
                        data[key][key2] = data[key][key2].replace("`", "'")
            elif isinstance(data[key], str):
                data[key] = data[key].replace("`", "'")

        while True:
            try:
                r = await client.post(url + object_name + '?$format=json', auth=auth, data=json.dumps(data))
                if ic(r.status_code) != 201:
                    if count_error >= 15:
                        count_error = 0
                        return 'Ошибка'
                    count_error += 1
                    await asyncio.sleep(5)
                    # Попробуем снова на следующей итерации цикла
                    continue
                elif object_name.find('Register') == -1:
                    data = r.json()
                    while True:
                        try:
                            x = await client.post(url + object_name + '(%27' + data['Ref_Key'] + '%27)/Post()', auth=auth)
                            if ic(x.status_code) != 200:
                                if count_error >= 15:
                                    count_error = 0
                                    return 'Ошибка'
                                count_error += 1
                                await asyncio.sleep(5)
                                # Попробуем снова на следующей итерации цикла
                                continue
                            else:
                                return r
                        except:
                            await asyncio.sleep(5)
            except:
                await asyncio.sleep(1)


async def send_odata_patch(object_name, data={}):
    async with httpx.AsyncClient() as client:
        url = dbconnect.odata_url
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        for key in data:
            if isinstance(data[key], dict):
                for key2 in data[key]:
                    if isinstance(data[key][key2], str):
                        data[key][key2] = data[key][key2].replace("`", "'")
            elif isinstance(data[key], str):
                data[key] = data[key].replace("`", "'")
        new_object_name = object_name.split("(")
        if object_name.find('Register') != -1:
            while True:
                try:
                    x = await client.delete(url + object_name.replace("`", "'"), auth=auth)
                    if x.status_code != 204:
                        await asyncio.sleep(5)
                        # Попробуем снова на следующей итерации цикла
                        continue
                    else:
                        break
                except:
                    await asyncio.sleep(1)
            while True:
                try:
                    r = await client.post(url + new_object_name[0] + '?$format=json', auth=auth, data=json.dumps(data))
                    if r.status_code != 200:
                        await asyncio.sleep(5)
                        # Попробуем снова на следующей итерации цикла
                        continue
                    else:
                        break
                except:
                    await asyncio.sleep(5)  # Попробуем снова на следующей итерации циклa
        else:
            while True:
                try:
                    r = await client.patch(
                        url + new_object_name[0] + "(guid" + new_object_name[1].replace("`", "%27") + '?$format=json',
                        auth=auth, data=json.dumps(data))
                    if r.status_code != 200:
                        await asyncio.sleep(5)
                        # Попробуем снова на следующей итерации цикла
                        continue
                    else:
                        try:
                            r = await client.post(url + new_object_name[0] + "(guid" + new_object_name[1].replace("`",
                                                                                                              "%27") + '/Post()',
                                              auth=auth, data="")
                            if r.status_code != 200:
                                await asyncio.sleep(5)
                                # Попробуем снова на следующей итерации цикла
                                continue
                            else:
                                break
                        except:
                            await asyncio.sleep(5)

                        break
                except:
                    await asyncio.sleep(5)

        return r


async def send_soap_req(soap_name):
    session = Session()
    session.auth = await sync_to_async(HTTPBasicAuth)(dbconnect.http_login, dbconnect.http_pwd)
    transport = await sync_to_async(Transport)(session=session, timeout=10)
    # return ic(session.post(dbconnect.soap_url + soap_name + '?wsdl', timeout=5))
    return await sync_to_async(Client)(dbconnect.soap_url + soap_name + '?wsdl', transport=transport)


class ContainerInfo(object):
    def __init__(self, message=''):
        self.LastViev = 'НЕТ'
        self.LastTemp = 'НЕТ'
        self.LastErr = 'НЕТ'
        self.Cargo = 'НЕТ'
        self.NewTemp = 'НЕТ'
        self.NewErr = 'НЕТ'
        self.LastGPS = 'НЕТ'
        self.RefJournalNum = 'НЕТ'
        self.RefKey = ''
        self.ResponceCode = ''
        self.ResponceText = ''
        self.ContType = 'НЕТ'
        if message == '':
            self.ContNum = 'НЕТ'
            self.ReqTemp = 'НЕТ'
            self.Status = 'НЕ ПОДКЛЮЧАЛСЯ'
            self.StatusDate = ''
        else:
            NewList = message.split("\n")
            self.ContNum = NewList[0]
            self.LastGPS = NewList[1]
            self.ReqTemp = NewList[3].split('|')[1].strip()
            self.Status = NewList[4].split('|')[1].strip()
            self.StatusDate = NewList[4].split('|')[2].strip()
            if len(NewList) > 5:
                self.LastViev = NewList[6].split('|')[1].strip()
                self.LastTemp = NewList[7].split('|')[1].strip()
                self.LastErr = NewList[8].split('|')[1].strip()
                self.Cargo = NewList[9].split('|')[1].strip()
                if len(NewList) > 10:
                    if NewList[10].split('|')[0].strip() == 'Журнал осмотра':
                        self.RefJournalNum = NewList[10].split('|')[1].strip()
                        self.RefJournalNum = self.RefJournalNum.split('@')[0]
                        if len(NewList) > 11:
                            self.NewTemp = NewList[12].split('|')[1].strip()
                            self.NewErr = NewList[13].split('|')[1].strip()
                    else:
                        self.NewTemp = NewList[11].split('|')[1].strip()
                        self.NewErr = NewList[12].split('|')[1].strip()
                if NewList[len(NewList) - 1].split('|')[0].strip() == 'Осмотр':
                    self.RefKey = NewList[len(NewList) - 1].split('|')[1].strip()

    def VarDump(self):
        return {
            'ResponceCode': self.ResponceCode,
            'ResponceText': self.ResponceText,
            'ContNum': self.ContNum,
            'ReqTemp': self.ReqTemp,
            'Status': self.Status,
            'StatusDate': self.StatusDate,
            'LastViev': self.LastViev,
            'LastTemp': self.LastTemp,
            'LastErr': self.LastErr,
            'Cargo': self.Cargo,
            'NewTemp': self.NewTemp,
            'NewErr': self.NewErr,
            'LastGPS': self.LastGPS,
            'RefJournalNum': self.RefJournalNum,
            'RefKey': self.RefKey,
            'ContType': self.ContType
        }

    def PrintHtml(self):
        HtmlText = '<strong>' + self.ContNum + '</strong>\n'  # 0
        HtmlText += '<strong>' + self.LastGPS + '</strong>\n'  # 1
        HtmlText += '<strong>===============================</strong>\n'  # 2

        if self.ReqTemp == 'НЕТ':
            HtmlText += 'Заявленная температура   | <strong>НЕТ</strong>\nСостояние <strong>| ' + self.Status + '</strong>\n'  # 3
        else:
            HtmlText += 'Заявленная температура   |        <strong>' + self.ReqTemp + '</strong>\n'  # 3
            HtmlText += 'Состояние |     <strong>' + self.Status + '</strong>     | <strong>' + str(
                self.StatusDate) + '</strong>\n'  # 4
            HtmlText += '<strong>===============================</strong>\n'  # 5
            HtmlText += 'Последний осмотр | <strong>' + str(self.LastViev) + '</strong>\n'  # 6
            HtmlText += 'Фактическая температура |        <strong>' + self.LastTemp + '</strong>\n'  # 7
            HtmlText += 'Последняя ошибка | <strong>' + self.LastErr + '</strong>\n'  # 8
            HtmlText += 'Груз | <strong>' + self.Cargo + '</strong>\n'  # 9
            if self.RefJournalNum != 'НЕТ':
                HtmlText += 'Журнал осмотра  | <strong>' + self.RefJournalNum + '</strong>\n'  # 10
            if self.NewTemp != 'НЕТ' or self.NewErr != 'НЕТ':
                HtmlText += '<strong>===============================</strong>\n'  # 11
                HtmlText += 'Новая температура | <strong>' + self.NewTemp + '</strong>\n'  # 12
                HtmlText += 'Новая ошибка |<strong>' + self.NewErr + '</strong>\n'  # 13
            if self.RefKey != '':
                HtmlText += '<strong>===============================</strong>\n'  # 11
                HtmlText += 'Осмотр | <strong>' + self.RefKey + '</strong>\n'  # 9

        return HtmlText

    async def FillContainerInfo(self):
        if self.RefKey == '':
            self.ResponceCode = -1
            self.responceText = 'Missing RefKey'
            return self.VarDump()
        else:
            text_request = {"filter": "Контейнер_Key eq guid`" + self.RefKey + "`",
                            "expand": "Свойство",
                            "select": "Свойство/PredefinedDataName, ЗначениеСвойства"}

            new_test = await send_odata_get("InformationRegister_СведенияОКонтейнере_RecordType/SliceLast",
                                      text_request)
            data = new_test.json()
            if len(data['value']) == 0:
                self.ResponceCode = -2
                self.ResponceText = 'Container not found by RefKey =' + self.RefKey
                return self.VarDump()
            text_gps = {"filter": "Груз eq cast(guid`" + self.RefKey + "`,`Catalog_Контейнеры`)",
                        "select": "МестоРазмещенияСтрокой"}
            new_gps = await send_odata_get("InformationRegister_РазмещенияГрузов_RecordType/SliceLast", text_gps)
            data_gps = new_gps.json()
            self.LastGPS = data_gps['value'][0]['МестоРазмещенияСтрокой']
            if self.LastGPS == '':
                self.ResponceCode = 1
                self.ResponceText = 'at ' + str(
                    datetime.now().strftime("%Y-%m-%dT%H:%M:%S")) + 'there is no container ' + self.ContNum
            self.ReqTemp = 'НЕТ'
            flag = True
            for i in range(len(data['value'])):
                if data['value'][i]['Свойство']['PredefinedDataName'] == 'Пустой':
                    if data['value'][i]['ЗначениеСвойства'] != 'false':
                        self.ResponceCode = 2
                        self.ResponceText = 'Container ' + self.ContNum + ' is empty'
                        return self.VarDump()
                elif data['value'][i]['Свойство']['PredefinedDataName'] == 'ТемпературныйРежим':
                    self.ReqTemp = data['value'][i]['ЗначениеСвойства'] if data['value'][i][
                                                                               'ЗначениеСвойства'] != '0' else 'НЕТ'
                elif data['value'][i]['Свойство']['PredefinedDataName'] == 'Груз':
                    self.Cargo = data['value'][i]['ЗначениеСвойства'] if data['value'][i][
                                                                             'ЗначениеСвойства'] != '' else 'НЕТ'

            if flag:
                self.ResponceCode = 0
                self.ResponceText = 'Container found.'
                # убедились что контейнер не порожний
                text_request = {"filter": "Контейнер_Key eq guid`" + self.RefKey + "`"}
                request = await send_odata_get("InformationRegister_СостояниеРефКонтейнера_RecordType/SliceLast",
                                         text_request)
                data = request.json()
                if data['value']:
                    status = data['value'][0]['Состояние']
                    TempDate = ''
                    xdt = datetime.strptime(data['value'][0]['Period'], '%Y-%m-%dT%H:%M:%S')
                    # проверяем последнее состояние согласно журналу реф техников
                    text_request = {"filter": "Контейнер_Key eq guid`" + self.RefKey + "`",
                                    "orderby": "ДатаОсмотра desc",
                                    "top": "1"}
                    new_test = await send_odata_get("Document_ЖурналОбходовРефов_Контейнеры",
                                              text_request)
                    data = new_test.json()

                    if data['value']:
                        dt = datetime.strptime(data['value'][0]['ДатаОсмотра'], '%Y-%m-%dT%H:%M:%S')
                        if str(dt) != '0001-01-01 00:00:00':
                            self.LastViev = dt.strftime("%H:%M %d.%m.%Y")
                            self.LastErr = str(data['value'][0]['Alarm']) if data['value'][0]['Alarm'] != '' else 'НЕТ'
                            self.LastTemp = str(data['value'][0]['ФактическаяT']) if data['value'][0][
                                                                                         'ФактическаяT'] != 0 else 'НЕТ'
                            self.Cargo = str(data['value'][0]['Груз']) if data['value'][0]['Груз'] != '' else 'НЕТ'
                        else:
                            self.LastViev = 'НЕТ'
                            self.LastErr = 'НЕТ'
                            self.LastTemp = 'НЕТ'

                    if status == 'Подключен':
                        self.Status = '⚡'
                        self.StatusDate = xdt.strftime("%H:%M %d.%m.%Y")
                    else:
                        self.Status = '🔌'
                        self.StatusDate = xdt.strftime("%H:%M %d.%m.%Y")
                else:
                    self.Status = 'Не подключался'
                    self.StatusDate = ''
                return self.VarDump()

    async def SearchByNum(self, numbers, Fulltext=False):
        if numbers == '':
            self.ResponceCode = -1
            self.ResponceText = 'Missing numbers argument `number`'
            return self.VarDump()

        if Fulltext == False:
            text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
                            "filter": "endswith(Контейнер/Description,`" + numbers + "`) eq true",
                            "expand": "Контейнер"}
        else:
            text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
                            "filter": "Контейнер/Description eq`" + numbers + "`",
                            "expand": "Контейнер"}
        new_test = await send_odata_get("AccumulationRegister_КонтейнерыНаТерминале/Balance", text_request)
        data = new_test.json()
        if len(data['value']) == 0:
            self.ResponceCode = -2
            self.ResponceText = 'Container not found by Number =' + numbers
            return self.VarDump()
        elif len(data['value']) == 1:
            self.RefKey = data['value'][0]['Контейнер']['Ref_Key']
            self.ContNum = data['value'][0]['Контейнер']['Description']
            self.ResponceCode = 0
            self.ResponceText = 'Container found by Number =' + numbers
            return self.VarDump()
        else:
            Responce = {
                'ResponceCode': 3,
                'ResponceText': 'by request number = `' + numbers + '` found many numbers',
                'Contlist': []}
            for i in range(len(data['value'])):
                Responce['Contlist'].append({'Ref_Key': data['value'][i]['Контейнер']['Ref_Key'],
                                             'Description': data['value'][i]['Контейнер']['Description']})
            return Responce

    async def SearchByNum2(self, numbers, Fulltext=False):
        if numbers == '':
            self.ResponceCode = -1
            self.ResponceText = 'Missing numbers argument `number`'
            return self.VarDump()
        if Fulltext == False:
            text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
                            "filter": "endswith(Контейнер/Description,`" + numbers + "`) eq true",
                            "expand": "Контейнер"}
        else:
            text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
                            "filter": "Контейнер/Description eq`" + numbers + "`",
                            "expand": "Контейнер"}
        new_test = await send_odata_get("AccumulationRegister_КонтейнерыНаТерминале/Balance", text_request)
        data = new_test.json()
        if len(data['value']) == 0:
            self.ResponceCode = -2
            self.ResponceText = 'Container not found by Number =' + numbers
            return self.VarDump()
        elif len(data['value']) == 1:
            self.RefKey = data['value'][0]['Контейнер']['Ref_Key']
            type_ref = await get_data(data['value'][0]['Контейнер']['Ref_Key'])
            type_ = await get_data(type_ref['#value']['Тип'])
            self.ContType = type_['#value']['Code']
            self.ContNum = data['value'][0]['Контейнер']['Description']
            self.ResponceCode = 0
            self.ResponceText = 'Container found by Number =' + numbers
            return self.VarDump()
        else:
            Responce = {
                'ResponceCode': 3,
                'ResponceText': 'by request number = `' + numbers + '` found many numbers',
                'Contlist': []}
            async with httpx.AsyncClient() as client:
                for i in range(len(data['value'])):
                    data['value'][i]['Контейнер']['Ref_Key']
                    type_ref = await get_data(data['value'][i]['Контейнер']['Ref_Key'])
                    type_ = await get_data(type_ref['#value']['Тип'])
                    Responce['Contlist'].append({'Ref_Key': data['value'][i]['Контейнер']['Ref_Key'],
                                                 'Description': data['value'][i]['Контейнер']['Description'],
                                                 'Type': type_['#value']['Code']})
            return Responce


async def cdAction(Ref_Key, User_Ref_Key, Action, Temp):
    Action = 'Подключение' if Action == 'Connect' else 'Отключение'
    now = datetime.now()
    long_text = {
        "Date": str(now.strftime("%Y-%m-%dT%H:%M:%S")),
        "ВидРаботыСРеф": Action,
        "ДатаВремя": str(now.strftime("%Y-%m-%dT%H:%M:%S")),
        "Контейнер_Key": str(Ref_Key),
        "ТемператураПеред": str(Temp),
        "ТемператураПосле": str(Temp),
        "ТемператураНормативная": str(Temp),
        "Автор": User_Ref_Key,
        "Автор_Type": "StandardODATA.Catalog_Сотрудники",
        "Статус": "Завершен",
        "Ответственный_Key": User_Ref_Key,
        "Комментарий": "",
        "Сотрудник_Key": User_Ref_Key
    }
    update_req = await send_odata_post('Document_РаботаСРефКонтейнерами', long_text)
